<?php

namespace App\Admin\Controllers\Game;

use App\Admin\Constant\GameConst;
use App\Admin\Controllers\Controller;
use App\Admin\Filters\Game\GameFilter;
use App\Admin\Models\Game\Game;
use App\Admin\Models\Game\GameCategory;
use App\Admin\Models\Game\GameGroup;
use App\Admin\Models\Game\GameVersion;
use App\Admin\Models\GameOperateLog;
use App\Admin\Requests\Game\GameRequest;
use App\Admin\Resources\Game\GameResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class GameController extends Controller
{
    /**
     * @param GameFilter $filter
     * @return \Illuminate\Http\JsonResponse
     * 游戏列表首页
     */
    public function index(GameFilter $filter)
    {
        $Games = Game::query()
            ->leftJoin('game_groups as gg', 'gg.id', '=', 'pid')
            ->leftJoin('cp', 'cp.id', '=', 'games.cp_id')
            ->leftJoin('game_versions as  gv', 'gv.app_id', '=', 'games.id')
            ->filter($filter)
            ->where(['games.is_delete' => 2])
            ->select('games.icon', 'games.cp_payback_url', 'gg.name as pName', 'games.id', 'games.created_at', 'games.updated_at', 'games.name', 'cp.company_name as cName', 'games.status', 'games.classify', 'gv.package_url')
            ->paginate();
        foreach ($Games as $k => $v) {
            $Games[$k]['package_url'] = $this->huo_get_ios_down_url($v['package_url']);
            $Games[$k]['icon'] = $this->huo_get_icon($v['icon']);
        }
        $data = [
            'data' => $Games,
            'sdkType' => $this->_sdkType(),
            'gameGroup' => $this->_gameGroup(),
            'status' => $this->_stauts(),
            'company' => $this->_company(),
            'name' => $this->_name(),
        ];
        return $this->ok(GameResource::collection($data));
    }


    /**
     * @param $id
     * @param Request $request
     * @param GameFilter $filter
     * @return \Illuminate\Http\JsonResponse
     * 添加回调地址
     */
    public function addPayBackUrl($id, Request $request, GameFilter $filter)
    {
        $url = $request->input();
        if (!$url) {
            return $this->errorMessage(GameConst::GAME_FAIL);
        }
        $res = Game::query()->where('id', $id)->update($url);
        if ($res) {

            if(isset($url['status'])){
                $remark  = '更改游戏状态';
                $type=2;
            }else if(isset($url['name'])){
                $remark  = '更改游戏名称';
                $type=2;
            }else{
                $remark  = '添加回调地址';
                $type=1;
            }
          return   $this->adminok(GameConst::GAME_SUCCESS,[],$remark,$id,$type);
        }
        return $this->errorMessage(GameConst::GAME_FAIL);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * 编辑页面
     */
    public function getEditList($id)
    {
        $data = Game::query()
            ->leftJoin('game_groups as gg', 'games.pid', '=', 'gg.id')
            ->leftJoin('cp', 'cp.id', '=', 'games.cp_id')
            ->leftJoin('game_versions', 'game_versions.app_id', '=', 'games.id')
            ->where(['games.id' => $id])
            ->select('gg.id as groupName', 'game_versions.package_url', 'games.name', 'game_versions.version', 'cp.id as company_name', 'games.category', 'games.icon', 'games.is_auth')
            ->get();
        $res = GameCategory::query()->where(['is_delete' => 2, 'type' => 2])->select('name', 'id')->distinct('name')->get();
        $data = $data->toArray();
        $data[0]['category'] = explode(',', $data[0]['category']);
        $data[0]['icon_name'] = '';
        foreach ($data[0]['category'] as $k => $v) {
            $data[0]['category'][$k] = (int)$v;

        }
        $result = [];
        $result['data'] = $data;
        $result['res'] = $res;
        return $this->ok($result);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * 上传icon
     */
    public function iconUpload($id)
    {
        $file = \request()->file('file');
        $realpath = $file->getRealPath();
        $extension = $file->getClientOriginalExtension();
        $fileName = $id . '-' . time() . '.' . $extension;
        if ($file->isValid()) {
            $bool = Storage::disk('uploads')->put("/icon/$fileName", file_get_contents($realpath));
            if ($bool) {
                return $this->adminok($fileName,[],'上传icon',$id,2);
            }
        }
        return $this->error();

    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * 编辑游戏
     */
    public function updateGame($id)
    {
        $request = request()->input();
        $res = Game::query()->where('name', $request['name'])->value('id');
        if ($res && $id != $res) {
            return $this->errorMessage(GameConst::GAME__EXIST);
        }
        $data = [
            'name' => $request['name'],
            'category' => array_count_values($request['category']) > 1 ? implode(',', $request['category']) : '',
            'is_auth' => $request['is_auth'],
            'icon' => !empty($request['icon_name']) ? HTTP . NEWDOMAIN . '/storage/' . $request['icon_name'] : '',
            'cp_id' => $request['company_name'],
            'pid' => $request['groupName'],
        ];

        if (empty($data['category'])) {
            unset($data['category']);
        }
        if (empty($data['icon'])) {
            unset($data['icon']);
        }


        Game::query()->where('id', $id)->update($data);
        $r = GameVersion::query()->where('app_id', $id)->exists();
        if (!$r) {
            GameVersion::query()->create([
                'app_id' => $id,
                'version' => empty($request['version']) ? '1.0' : $request['version'],
            ]);
        } else {
            GameVersion::query()->where('app_id', $id)->update([
                'version' => empty($request['version']) ? '1.0' : $request['version'],
            ]);
        }


        return $this->adminok(GameConst::GAME_GROUP_EDIT_SUCCESS,[],'更改游戏信息',$id,2);

    }


    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * 对接参数
     */
    public function getGameParams($id)
    {
        $data = Game::query()->where('id', $id)->select('app_key', 'id', 'name')->get();
        return $this->ok(GameResource::collection($data));
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * 获取操作记录
     */
    public function opreate(Request $request)
    {

        $data = $request->input('data');
        $id = $data['id'];
        $per_page = isset($data['per_page'])?$data['per_page']:15;
        $page =  isset($data['page'])?$data['page']:1;
        $data = DB::table('game_operate_logs')->where('app_id', $id)->paginate($per_page, $columns = ['*'], $pageName = 'page', $page);
//        $data = json_decode($data, true);
        foreach ($data as $k => $v) {
            if (preg_match('/\d+/', $v->action)) {
                preg_match('/(.*?)\d+/', $v->action, $matches);
                $data[$k]->action = $matches[0];
            }
            $data[$k]->create_time = date('Y-m-d H:i:s', $v->create_time);

        };
        $res = [];
        $res['data'] = $data;
        $res['meta'] = [
            'id'=>$id,
            'current_page'=>$data->currentPage(),
            'total'=>$data->total(),
            'per_page'=>$data->perPage(),

        ];
        return $this->ok($res);

    }


    function huo_get_ios_down_url($url)
    {
        if (0 === strpos($url, "http") || 0 === strpos($url, "https") || 0 === strpos($url, "itms-services") || $url == '') {
            return $url;
        }

        return DOWNIOSSITE . $url;
    }

    function huo_get_icon($url)
    {
        if (0 === strpos($url, "http") || 0 === strpos($url, "https") || $url == '') {
            return $url;
        }

        return STATICSITE . $url;
    }

    function _sdkType()
    {
        return [
            ['name' => '安卓', 'id' => GameConst::GAME_ANDROID],
            ['name' => 'ios', 'id' => GameConst::GAME_IOS],
            ['name' => 'H5', 'id' => GameConst::GAME_H5],
            ['name' => '小程序', 'id' => GameConst::GAME_XU],
        ];

    }

    function _gameGroup()
    {
        return GameGroup::query()->distinct()->select('name', 'id')->get();


    }

    function _stauts()
    {

        return [
            ['name' => '接入中', 'id' => GameConst::GAME_STATUS_ACCESS],
            ['name' => '上线', 'id' => GameConst::GAME_STATUS_ON],
            ['name' => '已下线', 'id' => GameConst::GAME_STATUS_OFF],
        ];

    }

    function _company()
    {
        return DB::table('cp')->distinct()->select('company_name', 'id')->get();


    }

    function _name()
    {
        return Game::query()->distinct()->select('name', 'id')->get();

    }


    public function create()
    {
        return $this->ok();
    }

    public function store(GameRequest $request)
    {
        $inputs = $request->validated();
        $request = request()->input();
        $exists  =Game::query()->where('name',$request['name'])->exists();
        if($exists){
            return $this->errorMessage(GameConst::GAME__EXIST);
        }
        $game = Game::query()->insertGetId([
            'name' => $request['name'],
            'pid' => $request['pid'],
            'cp_id' => $request['cp_id']

        ]);
        if (!$game) {
            return $this->errorMessage(GameConst::GAME_GROUP__ADD_FAIL);
        }

        return $this->adminok(GameConst::GAME_GROUP_EDIT_SUCCESS,[],$game,'添加游戏',1);
    }

    public function edit(Request $request, Game $Game)
    {
        return $this->ok(GameResource::make($Game));
    }

    public function update(GameRequest $request, Game $Game)
    {
        $inputs = $request->validated();
        $Game->update($inputs);

        return $this->created(GameResource::make($Game));
    }


    public function destroy($id)
    {
        Game::query()->where(['id' => $id])->update(['is_delete' => 1, 'delete_time' => time(), 'updated_at' => time()]);

        return $this->adminok(GameConst::GAME_DELETE_SUCCESS,[],'删除游戏',$id,3);
    }
}
